package cn.codingxiaxw.util;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

/**
 * 扫描package下所有的bean, 并生成对应的sql
 *
 * 直接跑main
 */
public class GenerateSqls {
    private static String DROP_SQL = "drop table if exists ";
    private static String CREATE_SQL = "create table ";

    private GenerateSqls() {
    }

    public static String bean2Sql(Class clazz) {
        StringBuilder sql = new StringBuilder();
        Field[] fields = clazz.getDeclaredFields();
        String tableName = fields[0].getDeclaringClass().getName();
        tableName = tableName.substring(tableName.lastIndexOf('.') + 1);
        tableName = tableName.substring(0, 1).toLowerCase() + tableName.substring(1);
        sql.append(DROP_SQL).append(tableName).append(";\n\n");
        sql.append(CREATE_SQL).append(tableName).append(" (\n");
        for (int i = 0; i < fields.length; i++) {
            if (i != fields.length - 1) {
                sql.append(fields[i].getName()).append(" ").append(getSqlType(fields[i].getType())).append(",\n");
            } else {
                sql.append(fields[i].getName()).append(" ").append(getSqlType(fields[i].getType())).append("\n);\n");
            }
        }
        return sql.toString();
    }

    private static String getSqlType(Class clazz) {
        if (clazz.isPrimitive()) {
            if (clazz.getName().equals("int")) return "int";
            if (clazz.getName().equals("short")) return "short";
            if (clazz.getName().equals("long")) return "long";

        } else {
            if (clazz.equals(Integer.class)) return "int";
            if (clazz.equals(Short.class)) return "short";
            if (clazz.equals(Long.class)) return "bigint";
            if (clazz.equals(String.class)) return "varchar(64)";
            if (clazz.equals(Date.class)) return "datetime";
        }
        return clazz.getName().substring(clazz.getName().lastIndexOf('.') + 1);
    }


    private static List<Class<?>> scanPackage(String packageFullName) {
        return ClassUtil.getClasses(packageFullName);
    }

    public static void main(String[] args) {
        List<Class<?>> classes = scanPackage("cn.codingxiaxw.entity");
        for (Class<?> aClass : classes) {
            System.out.println(bean2Sql(aClass));
        }
    }
}
